﻿
// RiskCopTestDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "RiskCopTest.h"
#include "RiskCopTestDlg.h"
#include "afxdialogex.h"

#include "adapt_data.pb.h"
#include "httpclient.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


string UTF8ToGBK(const std::string& strUTF8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
	WCHAR* wszGBK = new WCHAR[len + 1];
	memset(wszGBK, 0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)strUTF8.c_str(), -1, wszGBK, len);

	len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
	char *szGBK = new char[len + 1];
	memset(szGBK, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
	//strUTF8 = szGBK;  
	std::string strTemp(szGBK);
	delete[]szGBK;
	delete[]wszGBK;
	return strTemp;
}

string GBKToUTF8(const std::string& strGBK)
{
	string strOutUTF8 = "";
	WCHAR * str1;
	int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
	str1 = new WCHAR[n];
	MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
	n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
	char * str2 = new char[n];
	WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
	strOutUTF8 = str2;
	delete[]str1;
	str1 = NULL;
	delete[]str2;
	str2 = NULL;
	return strOutUTF8;
}

int64_t get_current_datedata()
{
	auto      now = std::chrono::system_clock::now();
	auto      tt = std::chrono::system_clock::to_time_t(now);
	struct tm ptm;

	// thread-safe function
#if defined(_WIN32)
	localtime_s(&ptm, &tt);
#elif defined(__unix__) || defined(__linux__)
	localtime_r(&tt, &ptm);
#endif  // WIN32

	return ((1900 + ptm.tm_year) * 100 + (ptm.tm_mon + 1)) * 100 + (ptm.tm_mday);
}

int64_t get_current_datetime()
{
	auto      now = std::chrono::system_clock::now();
	auto      tt = std::chrono::system_clock::to_time_t(now);
	struct tm ptm;

	// thread-safe function
#if defined(_WIN32)
	localtime_s(&ptm, &tt);
#elif defined(__unix__) || defined(__linux__)
	localtime_r(&tt, &ptm);
#endif  // WIN32

	return ((ptm.tm_hour) * 60 + (ptm.tm_min)) * 60 + (ptm.tm_sec);
}
//#include <boost/beast/core.hpp>
//#include <boost/beast/http.hpp>
//#include <boost/beast/version.hpp>
//#include <boost/asio/connect.hpp>
//#include <boost/asio/ip/tcp.hpp>

using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
//namespace http = boost::beast::http;

/*int getUrl()
{
	try
	{
		auto const host = "www.baidu.com";		//要访问的主机名
		auto const port = "80";					//http服务端口
		auto const target = "/loading.html";	//要获取的文档
		int version = 11;

		// The io_context is required for all I/O
		boost::asio::io_context ioc;

		// These objects perform our I/O
		tcp::resolver resolver{ ioc };
		tcp::socket socket{ ioc };

		// Look up the domain name
		auto const results = resolver.resolve(host, port);

		// Make the connection on the IP address we get from a lookup
		boost::asio::connect(socket, results.begin(), results.end());

		// Set up an HTTP GET request message
		http::request<http::string_body> req{ http::verb::get, target, version };
		req.set(http::field::host, host);
		req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

		// Send the HTTP request to the remote host
		http::write(socket, req);

		// This buffer is used for reading and must be persisted
		boost::beast::flat_buffer buffer;

		// Declare a container to hold the response
		http::response<http::dynamic_body> res;

		// Receive the HTTP response
		http::read(socket, buffer, res);


		// Write the message to standard out
		std::cout << res << std::endl;

		// Gracefully close the socket
		boost::system::error_code ec;
		socket.shutdown(tcp::socket::shutdown_both, ec);

		// not_connected happens sometimes
		// so don't bother reporting it.
		//
		if (ec && ec != boost::system::errc::not_connected)
			throw boost::system::system_error{ ec };

		// If we get here then the connection is closed gracefully
	}
	catch (std::exception const& e)
	{
		std::cerr << "Error: " << e.what() << std::endl;
		return EXIT_FAILURE;
	}
	return EXIT_SUCCESS;

}*/
class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

	// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
public:

};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)

END_MESSAGE_MAP()


// CRiskCopTestDlg 对话框



CRiskCopTestDlg::CRiskCopTestDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_RISKCOPTEST_DIALOG, pParent), work_(io_service_)
	, m_strIP(_T("192.168.2.2"))
	, write_check(FALSE)
	, m_strHqPort(_T("10317"))
	, m_strOrderPort(_T("14097"))
	, m_strFreq(_T("2"))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CRiskCopTestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_strIP);
	DDX_Check(pDX, IDC_CHECK1, write_check);
	DDX_Text(pDX, IDC_EDIT2, m_strHqPort);
	DDX_Text(pDX, IDC_EDIT3, m_strOrderPort);
	DDX_Text(pDX, IDC_EDIT4, m_strFreq);
}

BEGIN_MESSAGE_MAP(CRiskCopTestDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON1, &CRiskCopTestDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CRiskCopTestDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CRiskCopTestDlg::OnBnClickedButton3)
	ON_BN_CLICKED(IDC_BUTTON4, &CRiskCopTestDlg::OnBnClickedButton4)
	ON_WM_DESTROY()
	//ON_EN_CHANGE(IDC_EDIT4, &CRiskCopTestDlg::OnEnChangeEdit4)
	ON_BN_CLICKED(IDC_CHECK3, &CRiskCopTestDlg::OnBnClickedCheck3)
END_MESSAGE_MAP()


// CRiskCopTestDlg 消息处理程序

BOOL CRiskCopTestDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	payload_send_buffer_ = new char[10 * 1024];

	CButton* pBtn = (CButton*)GetDlgItem(IDC_CHECK2);
	if (pBtn) { pBtn->SetCheck(true); }

	//string strRet;
	//cloud::downloader::download("qt.gtimg.cn","/q=sh600000", strRet);

	m_strFileName = GetModuleDir();
	m_strFileName += "\\testdata.xlsx";

	m_strFileName = GBKToUTF8(m_strFileName);

	strAdr_ = m_strIP;

	cur_order_row_ = 1;
	cur_cancel_row_ = 1;
	cur_bargain_row_ = 1;
	cur_sheet_id_ = 0;


	boost::thread mainthread(boost::bind(&boost::asio::io_service::run, &io_service_));
	mainthread.detach();


	SetTimer(1, 2000, NULL);
	SetTimer(2, 3000, NULL);
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

CString CRiskCopTestDlg::GetModuleDir()
{
	HMODULE module = GetModuleHandle(0);
	char pFileName[MAX_PATH] = { 0 };
	GetModuleFileName(module, pFileName, MAX_PATH);
	CString csFullName(pFileName);
	int nPos = csFullName.ReverseFind('\\');
	if (nPos < 0)
		return CString("");
	else
		return csFullName.Left(nPos);
}


void CRiskCopTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CRiskCopTestDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CRiskCopTestDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

BOOL CRiskCopTestDlg::PreTranslateMessage(MSG* pMsg)
{
	if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_RETURN))
	{
		HWND hwnd1 = ((CEdit*)GetDlgItem(IDC_EDIT4))->m_hWnd;
		if (pMsg->hwnd == hwnd1)
		{
			UpdateData(TRUE);
			int nTime = atol(m_strFreq.GetBuffer(0)) * 1000;
			if (nTime > 0)
			{
				KillTimer(1);
				SetTimer(1, nTime, nullptr);
			}
		}
		return TRUE;
	}
	return CDialog::PreTranslateMessage(pMsg);
}

bool b_run_loop = false;

void CRiskCopTestDlg::OnBnClickedButton1()
{
	UpdateData(TRUE);
	strAdr_ = m_strIP;
	strHqPort_ = m_strHqPort;

	client_qh_ptr_.reset(new TcpClient(io_service_, strAdr_, strHqPort_));
	client_qh_ptr_->connect_agent_server();


	cur_sheet_id_ = 0;

	if (!b_run_loop)
	{

		b_run_loop = true;
	}
}


void CRiskCopTestDlg::OnBnClickedButton2()
{
	UpdateData(TRUE);
	strAdr_ = m_strIP;
	strOrderPort_ = m_strOrderPort;

	client_order_ptr_.reset(new TcpClient(io_service_, strAdr_, strOrderPort_));
	client_order_ptr_->connect_agent_server();

	cur_order_row_ = 1;
	cur_cancel_row_ = 1;
	cur_bargain_row_ = 1;

	cur_sheet_id_ = 0;
	/*if (!b_run_loop)
	{
		boost::thread mainthread(boost::bind(&boost::asio::io_service::run, &io_service_));
		mainthread.detach();

		b_run_loop = true;
	}*/
}
void CRiskCopTestDlg::OnBnClickedButton3()
{
	if (client_qh_ptr_)
		client_qh_ptr_->disconnect_agent_server();
}


void CRiskCopTestDlg::OnBnClickedButton4()
{
	if (client_order_ptr_)
		client_order_ptr_->disconnect_agent_server();

}
void CRiskCopTestDlg::OnTimer(UINT_PTR nIDEvent)
{
	if (nIDEvent == 1)
	{
		CButton* pCheck = (CButton*)GetDlgItem(IDC_CHECK3);
		if (pCheck->GetCheck())
		{
			ReadAndSeqSend();
		}
		else
		{
			ReadAndSend();
		}

		CStatic* pLog = (CStatic*)GetDlgItem(IDC_STATIC_HQ);
		if (pLog)
		{
			if (client_qh_ptr_)
				pLog->SetWindowText(client_qh_ptr_->msg_info_.c_str());
		}
		pLog = (CStatic*)GetDlgItem(IDC_STATIC_ORDER);
		if (pLog)
		{
			if (client_order_ptr_)
				pLog->SetWindowText(client_order_ptr_->msg_info_.c_str());
		}

		pLog = (CStatic*)GetDlgItem(IDC_STATICSEND);
		if (pLog)
		{
			pLog->SetWindowText(strSendinfo_);
		}
		
	}
	if (nIDEvent == 2)
	{
		CButton* pCheck = (CButton*)GetDlgItem(IDC_CHECK3);
		if (!pCheck->GetCheck())
			GetTenXunHqSend();
	}
	CDialogEx::OnTimer(nIDEvent);
}

void CRiskCopTestDlg::GetTenXunHqSend()
{
	struct cellPos
	{
		string strCode;
		int col;
		int row;
	};
	vector<cellPos> temCellVec;
	string strUrl = "/q=";
	xlnt::workbook wb;
	wb.load(m_strFileName);
	xlnt::worksheet ws = wb.sheet_by_title(GBKToUTF8("行情"));
	int nMaxRow = 200;
	for (int i = 2; i < nMaxRow; i++)
	{
		//xlnt::cell temcell = ws.cell(0, i);
		//auto cell = ws.cell(xlnt::cell_reference(0, 1));
		auto cell = ws.cell(xlnt::cell_reference(1, i));
		if (cell.has_value())
		{
			string strCode = cell.to_string();
			strUrl += strCode;
			strUrl += ",";

			cellPos item;
			item.strCode = strCode;
			item.col = 2;
			item.row = i;
			temCellVec.push_back(item);
		}
		else
		{
			break;
		}
	}
	strUrl.erase(strUrl.size() - 1, 1);
	string strContent;
	if (strUrl.size() > 10)
		cloud::downloader::download("qt.gtimg.cn", strUrl, strContent);
	if (strContent.size() > 10)
	{
		adapter::pb::YusurHqDetail  cur_hq_detail;

		int nRecvID = 0;
		char* pszContent = (char*)strContent.c_str();
		char* pSingle = strstr(pszContent, ";");	//pszContent不变
		while (pSingle != NULL)
		{
			char szLine[1024] = { 0 };
			strncpy(szLine, pszContent, pSingle - pszContent);
			{
				std::string strName;
				char* pszLine = szLine;
				char* pItem = strtok(pszLine, "~");
				if (pItem)
				{
					//这里有BUG
					//var hq_str_s_sh600263="股票名称"，53.6;
					//var hq_str_s_sh600263="";
					bool bKCB = false;
					strName.assign(pItem);
					pszLine = pszLine + strName.size() + 1;	//已指向数据了	
					int lNameID = 0;
					int nStockID = 0;
					std::string strGoodID;
					int nFind = strName.find_last_of('=');
					if (nFind > 6)
					{
						char cMarket = 0;
						strGoodID = strName.substr(nFind - 8, 8);
						int nFind = strGoodID.find("sz");
						if (nFind >= 0)
							cMarket = 1;
						lNameID = atol(strGoodID.substr(2).c_str());

						nStockID = cMarket * 1000000 + lNameID;
						long l = nStockID / 10000;
						if (l == 68)
						{
							bKCB = true;
						}
					}
					CStock* pStock = stock_manager_.GetStock(strGoodID);
					if (nullptr == pStock)
					{
						pStock = new CStock(strGoodID, bKCB);
						stock_manager_.AddStock(strGoodID, pStock);
					}
					if (client_qh_ptr_ && pStock->Decode(pszLine, client_qh_ptr_))
					{
						adapter::pb::IndexVolume* ptemIndexVol = cur_hq_detail.add_index_volume_vec();
						ptemIndexVol->set_stock_id(lNameID);
						ptemIndexVol->set_volume(pStock->cur_volumn_);

					}
				}
			}
			pszContent = pSingle + 1;    //加强表示为";"
			pSingle = strstr(pszContent, ";");
			nRecvID++;
		}
		if (cur_hq_detail.index_volume_vec_size() > 0)
		{
			cur_hq_detail.set_timestamp_id(get_current_datetime());

			int length = cur_hq_detail.ByteSize();
			cur_hq_detail.SerializeToArray(payload_send_buffer_, length);

			PackHead pack;
			int nT = sizeof(PackHead);
			pack.nVersion = 1011;
			pack.nType = MSG_YUSUR_Detail;
			pack.nLen = length;

			if (client_qh_ptr_)
			{
				client_qh_ptr_->SendMsg((char*)&pack, nT);
				client_qh_ptr_->SendMsg(payload_send_buffer_, length);

			}
		}
		CButton* pBtn = (CButton*)GetDlgItem(IDC_CHECK1);
		if (pBtn && pBtn->GetCheck())
		{
			for (auto& item : temCellVec)
			{
				CStock* pStock = stock_manager_.GetStock(item.strCode);
				if (pStock)
				{
					auto cell = ws.cell(xlnt::cell_reference(item.col, item.row));
					cell.value(pStock->cur_price_);
				}
			}
			//wps打开后会报错
			wb.save(m_strFileName);
		}
	}

}

void CRiskCopTestDlg::ReadAndSend()
{
	xlnt::workbook wb;
	wb.load(m_strFileName);
	xlnt::worksheet ws = wb.active_sheet();
	string strTile = UTF8ToGBK(ws.title());

	if (strTile == "委托")
	{
		SendOrder(ws);
	}
	if (strTile == "撤单回报")
	{
		SendCancel(ws);
	}
	if (strTile == "成交")
	{
		SendBargain(ws);
	}
	/*for (xlnt::cell_vector cell_vec : ws)   //一行
	{
		for (xlnt::cell cell : cell_vec)   //一列
		{
			string strValue = cell.to_string();
		}
	}
	int test = 0;
	for (auto row : ws.rows(false))
	{
		test++;
		for (auto cell : row)
		{

		}
	}*/
}

void CRiskCopTestDlg::ReadAndSeqSend()
{
	xlnt::workbook wb;
	wb.load(m_strFileName);
	int nTotalSheet = wb.sheet_count();
	if (cur_sheet_id_ >= nTotalSheet)
	{
		//cur_sheet_id_ = 0;
		strSendinfo_.Format("顺序发送页面结束,共发%d页", cur_sheet_id_);
		CStatic* pLog = (CStatic*)GetDlgItem(IDC_STATICSEND);
		if (pLog)
		{
			pLog->SetWindowText(strSendinfo_);
		}
		return;
	}
	xlnt::worksheet ws = wb.sheet_by_index(cur_sheet_id_);
	string strTile = UTF8ToGBK(ws.title());
	int nFind = strTile.find("委托");
	if (nFind >= 0)
	{
		SendOrder(ws);
	}
	else
	{
		nFind = strTile.find("撤单");
		if (nFind >= 0)
		{
			SendCancel(ws);
		}
		else
		{
			nFind = strTile.find("成交");
			if (nFind >= 0)
			{
				SendBargain(ws);
			}
			else
			{
				nFind = strTile.find("行情");
				if (nFind >= 0)
				{
					SendHqData(ws);
				}
				else
				{
					cur_sheet_id_++;
				}
			}
		}
	}
}

void CRiskCopTestDlg::SendOrder(xlnt::worksheet& ws)
{
	int nMaxRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		nMaxRow++;
	}
	if (cur_order_row_ >= nMaxRow)
	{
		CButton* pBtn = (CButton*)GetDlgItem(IDC_CHECK2);
		if (pBtn && pBtn->GetCheck())
		{
			cur_order_row_ = 1;
		}
		else
		{
			strSendinfo_.Format("发送委托数据结束,共发%d行", cur_order_row_ - 1);
			cur_sheet_id_++;
		}
	}

	nMaxRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		if (nMaxRow == cur_order_row_)
		{
			int nCol = 0;
			YusurOrderCheckRequest info;
			info.MsgType = 1;
			info.MsgLen = sizeof(YusurOrderCheckRequest);
			info.Reserved = 0;
			for (xlnt::cell cell : cell_vec)          //一列
			{
				string strValue = cell.to_string();
				if (nCol == 0)
					info.ExternSysNo = atol(strValue.c_str());
				if (nCol == 1)
					info.ExternReportNo = atol(strValue.c_str());
				if (nCol == 2)
					info.EntrustDate = get_current_datedata();
				if (nCol == 3)
					info.BusinessTime = get_current_datetime();
				if (nCol == 4)
					strcpy(info.StockAccount, strValue.c_str());
				if (nCol == 5)
					info.ExchangeType = atol(strValue.c_str());
				if (nCol == 6)
					strcpy(info.SecurityCode, strValue.c_str());
				if (nCol == 7)
					info.EntrustDirection = atol(strValue.c_str());
				if (nCol == 8)
					info.EntrustAmount = atol(strValue.c_str());
				if (nCol == 9)
					info.PriceType = atol(strValue.c_str());
				if (nCol == 10)
					info.EntrustPrice = atof(strValue.c_str()) * 10000;
				if (nCol == 11)
					info.EntrustBalance = _atoi64(strValue.c_str());
				if (nCol == 12)
					info.NodeId = atol(strValue.c_str());
				if (nCol == 13)
					info.FunctionID = atol(strValue.c_str());
				nCol++;
			}
			if (info.BusinessTime > 0 && info.EntrustAmount > 0 && info.EntrustPrice > 0 && info.ExternSysNo > 0)
			{
				std::ostringstream os_contentData;
				YuSur_Serializate::Serialization_Text_Helper<YusurOrderCheckRequest>(info, os_contentData);
				string strContent = os_contentData.str();
				int nBody = sizeof(YusurOrderCheckRequest);

				PackHead pack;
				int nT = sizeof(PackHead);
				pack.nVersion = 1011;
				pack.nType = MSG_YUSUR_ORDERCHECKREQ;
				pack.nLen = nBody;
				std::ostringstream os_outData;
				YuSur_Serializate::Serialization_Text_Helper<PackHead>(pack, os_outData);
				string strHead = os_outData.str();
				int nSize = strHead.size();
				if (client_order_ptr_)
				{
					//client_order_ptr_->SendMsg(strHead);
					//client_order_ptr_->SendMsg(strContent);

					if (client_order_ptr_->get_connect_status())
					{
						client_order_ptr_->SendMsg((char*)&pack, nT);
						bool bRet = client_order_ptr_->SendMsg((char*)&info, sizeof(info));
						strSendinfo_.Format("发送委托数据，正在发送第%d行", cur_order_row_);
						cur_order_row_++;
					}
					else
					{
						strSendinfo_.Format("断开连接,未发送数据");
					}
				}
			}
			break;
		}
		nMaxRow++;
	}

}

void CRiskCopTestDlg::SendCancel(xlnt::worksheet& ws)
{
	int nMaxRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		nMaxRow++;
	}
	if (cur_cancel_row_ >= nMaxRow)
	{
		CButton* pBtn = (CButton*)GetDlgItem(IDC_CHECK2);
		if (pBtn && pBtn->GetCheck())
		{
			cur_cancel_row_ = 1;
		}
		else
		{
			strSendinfo_.Format("发送撤单数据结束，共发送%d行", cur_cancel_row_ - 1);
			cur_sheet_id_++;
		}
	}
	//ws.cell(xlnt::cell_reference(fIn + 1, fOut + 1))


	nMaxRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		if (nMaxRow == cur_cancel_row_)
		{
			int nCol = 0;
			YusurOrderCancelRsp info;
			info.MsgType = 10012;
			info.MsgLen = sizeof(YusurOrderCancelRsp);
			info.ExternSysNo = 0;
			info.ExternReportNo = 0;
			info.OriginalOrderNum = 0;
			info.ExchangeOrderId = 0;
			info.Reserved = 0;
			for (xlnt::cell cell : cell_vec)          //一列
			{
				string strValue = cell.to_string();
				if (nCol == 0)
					info.OriginalExternSysNo = atol(strValue.c_str());
				if (nCol == 1)
					info.OriginalExternReportNo = atol(strValue.c_str());
				if (nCol == 2)
					info.Result = atol(strValue.c_str());
				if (nCol == 3)
					info.CancelOrderNum = atol(strValue.c_str());
				if (nCol == 4)
					info.NodeId = atol(strValue.c_str());
				if (nCol == 5)
					info.FunctionID = atol(strValue.c_str());
				nCol++;
			}
			if (info.OriginalExternSysNo > 0 && info.OriginalExternReportNo > 0 && info.FunctionID > 0)
			{
				std::ostringstream os_contentData;
				YuSur_Serializate::Serialization_Text_Helper<YusurOrderCancelRsp>(info, os_contentData);
				string strContent = os_contentData.str();
				int nBody = sizeof(YusurOrderCancelRsp);

				PackHead pack;
				int nT = sizeof(PackHead);
				pack.nVersion = 1011;
				pack.nType = MSG_YUSUR_ORDERCANCELRSP;
				pack.nLen = nBody;
				std::ostringstream os_outData;
				YuSur_Serializate::Serialization_Text_Helper<PackHead>(pack, os_outData);
				string strHead = os_outData.str();
				int nSize = strHead.size();
				if (client_order_ptr_)
				{
					//client_order_ptr_->SendMsg(strHead);
					//client_order_ptr_->SendMsg(strContent);

					if (client_order_ptr_->get_connect_status())
					{
						client_order_ptr_->SendMsg((char*)&pack, nT);
						bool bRet = client_order_ptr_->SendMsg((char*)&info, sizeof(info));
						strSendinfo_.Format("发送撤单数据，正在发送第%d行", cur_cancel_row_);
						cur_cancel_row_++;
					}
					else
					{
						strSendinfo_.Format("断开连接,未发送数据");
					}

				}

			}
			break;
		}
		nMaxRow++;
	}

}

void CRiskCopTestDlg::SendBargain(xlnt::worksheet& ws)
{
	int nMaxRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		nMaxRow++;
	}
	if (cur_bargain_row_ >= nMaxRow)
	{
		CButton* pBtn = (CButton*)GetDlgItem(IDC_CHECK2);
		if (pBtn && pBtn->GetCheck())
		{
			cur_bargain_row_ = 1;
		}
		else
		{
			strSendinfo_.Format("发送成交数据结束，共发送%d行", cur_bargain_row_ - 1);
			cur_sheet_id_++;
		}
	}

	//ws.cell(xlnt::cell_reference(fIn + 1, fOut + 1))

	nMaxRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		if (nMaxRow == cur_bargain_row_)
		{
			int nCol = 0;
			YusurOrderDealInfo info = { 0 };
			info.MsgType = 10021;
			info.MsgLen = sizeof(YusurOrderDealInfo);
			info.Reserved = 0;
			for (xlnt::cell cell : cell_vec)          //一列
			{
				string strValue = cell.to_string();
				if (nCol == 0)
					info.ExternSysNo = atol(strValue.c_str());
				if (nCol == 1)
					info.ExternReportNo = atol(strValue.c_str());
				if (nCol == 2)
					info.NodeId = atol(strValue.c_str());
				if (nCol == 3)
					info.DealNo = atol(strValue.c_str());
				if (nCol == 4)
					strcpy(info.StockAccount, strValue.c_str());
				if (nCol == 5)
					strcpy(info.SecurityCode, strValue.c_str());
				if (nCol == 6)
					info.EntrustDirection = atol(strValue.c_str());
				if (nCol == 7)
					info.BusinessPrice = atof(strValue.c_str()) * 10000;
				if (nCol == 8)
					info.BusinessAmount = atol(strValue.c_str());
				if (nCol == 9)
					info.ExternDealNo = atol(strValue.c_str());
				if (nCol == 10)
					info.BusinessTime = get_current_datetime();
				if (nCol == 11)
					info.FunctionID = atol(strValue.c_str());
				nCol++;
			}
			if (info.BusinessTime > 0 && info.BusinessAmount > 0 && info.BusinessPrice > 0 && info.ExternSysNo > 0)
			{
				std::ostringstream os_contentData;
				YuSur_Serializate::Serialization_Text_Helper<YusurOrderDealInfo>(info, os_contentData);
				string strContent = os_contentData.str();
				int nBody = sizeof(YusurOrderDealInfo);

				PackHead pack = { 0 };
				int nT = sizeof(PackHead);
				pack.nVersion = 1011;
				pack.nType = MSG_YUSUR_ORDERDEALINFO;
				pack.nLen = nBody;
				std::ostringstream os_outData;
				YuSur_Serializate::Serialization_Text_Helper<PackHead>(pack, os_outData);
				string strHead = os_outData.str();
				int nSize = strHead.size();
				if (client_order_ptr_)
				{
					//client_order_ptr_->SendMsg(strHead);
					//client_order_ptr_->SendMsg(strContent);

					if (client_order_ptr_->get_connect_status())
					{
						client_order_ptr_->SendMsg((char*)&pack, nT);
						bool bRet = client_order_ptr_->SendMsg((char*)&info, nBody);
						strSendinfo_.Format("发送成交数据，正在发送第%d行", cur_bargain_row_);
						cur_bargain_row_++;
					}
					else
					{
						strSendinfo_.Format("断开连接,未发送数据");
					}

				}

			}
			break;
		}
		nMaxRow++;
	}

}
//整个 sheet全部发送
void CRiskCopTestDlg::SendHqData(xlnt::worksheet& ws)
{
	adapter::pb::YusurHqDetail  cur_hq_detail;
	int nRow = 0;
	for (xlnt::cell_vector cell_vec : ws)
	{
		if (nRow >= 1)
		{
			int nCol = 0;
			string strGoodID = "";
			float tempData[32] = { 0 };
			for (xlnt::cell cell : cell_vec)          //一列
			{
				string strValue = cell.to_string();
				if (nCol == 0)
					strGoodID = strValue;
				else
				{
					tempData[nCol-1] = atof(strValue.c_str());
				}
				nCol++;
			}
		
			CStock* pStock = stock_manager_.GetStock(strGoodID);
			if (nullptr == pStock)
			{
				pStock = new CStock(strGoodID, false);
				stock_manager_.AddStock(strGoodID, pStock);
			}
			if (client_qh_ptr_ && pStock->DecodeValue(tempData, client_qh_ptr_))
			{
				int lNameID = atol(strGoodID.substr(2).c_str());
				
				adapter::pb::IndexVolume* ptemIndexVol = cur_hq_detail.add_index_volume_vec();
				ptemIndexVol->set_stock_id(lNameID);
				ptemIndexVol->set_volume(pStock->cur_volumn_);
				
			}
			if (client_qh_ptr_)
			{
				strSendinfo_.Format("发送 %s 行情数据", strGoodID.c_str());
				CStatic* pLog = (CStatic*)GetDlgItem(IDC_STATICSEND);
				if (pLog)
				{
					pLog->SetWindowText(strSendinfo_);
					pLog->Invalidate();
				}
			}
		}
		nRow++;
	}
	if (cur_hq_detail.index_volume_vec_size() > 0)
	{
		cur_hq_detail.set_timestamp_id(get_current_datetime());

		int length = cur_hq_detail.ByteSize();
		cur_hq_detail.SerializeToArray(payload_send_buffer_, length);

		PackHead pack;
		int nT = sizeof(PackHead);
		pack.nVersion = 1011;
		pack.nType = MSG_YUSUR_Detail;
		pack.nLen = length;

		if (client_qh_ptr_)
		{
			client_qh_ptr_->SendMsg((char*)&pack, nT);
			client_qh_ptr_->SendMsg(payload_send_buffer_, length);

			strSendinfo_.Format("发送行情逐笔数据,时间 %d", cur_hq_detail.timestamp_id());

			CStatic* pLog = (CStatic*)GetDlgItem(IDC_STATICSEND);
			if (pLog)
			{
				pLog->SetWindowText(strSendinfo_);
			}
		}
	}
	if (client_qh_ptr_)
	{
		cur_sheet_id_++;
	}
}

void CRiskCopTestDlg::OnDestroy()
{
	CDialogEx::OnDestroy();
	if (payload_send_buffer_)
	{
		delete payload_send_buffer_;
		payload_send_buffer_ = nullptr;
	}

	OnBnClickedButton3();
	OnBnClickedButton4();

	io_service_.stop();

}

void CRiskCopTestDlg::OnBnClickedCheck3()
{
	CButton* pBtn = (CButton*)GetDlgItem(IDC_CHECK2);
	if (pBtn)
	{
		pBtn->SetCheck(false);
	}
}
